package com.coolham.common.network;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;

import com.coolham.common.util.DeviceInfoUtil;

public class LoginToMaotoud extends Thread {
	final static String TAG = "LoginToMaotoud";

	private Context mContext;
	private DeviceInfoUtil deviceInfo;

	public LoginToMaotoud(Context context) {
		this.mContext = context;
		deviceInfo = new DeviceInfoUtil(mContext);

	}

	public void run() {
		Log.v(TAG, ">>>run...");
		doLogin();
	}

	private void doLogin() {
		HashMap<String, String> reqMap = prepareHeaderData();

		HashMap<String, Object> res = null;

		HttpParams httpParameters = getHttpParameters();

		HttpClient httpClient = new DefaultHttpClient(httpParameters);

		checkNetworkType();

		String serverUrl = "http://maotoud.appspot.com/maotoud";
		String requestUrl = serverUrl + "/login";

		Log.v(TAG, "requestUrl=" + requestUrl);

		// HttpGet httpRequest = new HttpGet(requestUrl);
		HttpPost httpRequest = new HttpPost(requestUrl);

		setHeaders(httpRequest, reqMap);

		HttpEntity entity = prepareHttpBody();
		httpRequest.setEntity(entity);

		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);

			procHttpResult(httpResponse);

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}

	}

	private void checkNetworkType() {
		/*
		 * NetworkInfo networkInfo = getCurrentNetStatus();
		 * 
		 * if (networkInfo != null &&
		 * networkInfo.getTypeName().equals("MOBILE")) {
		 * //netWorkInfo.getExtraInfo().equals("cmwap") //HttpHost proxy = new
		 * HttpHost( "10.0.0.172", 80, "http");
		 * //httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
		 * proxy); }
		 * 
		 * Log.v(TAG, "Network:" + networkInfo.toString());
		 */
	}

	private void procHttpResult(HttpResponse httpResponse) {
		int code = httpResponse.getStatusLine().getStatusCode();
		Log.v(TAG, ">>> code=" + code);
		switch (code) {
		case HttpStatus.SC_OK:
			HashMap<String, String> resMap = getHeaders(httpResponse);
			String result = resMap.get("Result");
			Log.v(TAG, ">>> result=" + result);

			byte[] bResultXml = null;
			try {
				bResultXml = EntityUtils.toByteArray(httpResponse.getEntity());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (bResultXml != null) {
				try {
					String strXml = new String(bResultXml, "utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
		case HttpStatus.SC_NOT_FOUND:
			Log.v(TAG, ">>> http not found");
			break;
		default:
			Log.v(TAG, ">>> unknown code:" + code);
		}
	}

	private HttpEntity prepareHttpBody() {
		ContentProducer cp = new ContentProducer() {
			public void writeTo(OutputStream outstream) throws IOException {
				Writer writer = new OutputStreamWriter(outstream, "UTF-8");
				writer.write("");
				writer.flush();
				writer.close();
			}
		};

		HttpEntity entity = new EntityTemplate(cp);
		return entity;
	}

	private HttpParams getHttpParameters() {
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 30 * 1000);
		HttpConnectionParams.setSoTimeout(httpParameters, 10 * 1000);
		HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);
		return httpParameters;
	}

	private HashMap<String, String> prepareHeaderData() {
		HashMap<String, String> reqMap = new HashMap<String, String>();

		reqMap.put("Version", "1.0");
		reqMap.put("Device-Type", "device");
		reqMap.put("Platform", "platform");
		reqMap.put("IMEI", deviceInfo.getIMEI());
		reqMap.put("IMSI", deviceInfo.getIMSI());
		return reqMap;
	}

	private HashMap<String, String> getHeaders(HttpResponse httpResponse) {
		HashMap<String, String> headers = new HashMap<String, String>();

		HeaderIterator iterator = httpResponse.headerIterator();
		while (iterator.hasNext()) {

			Header header = iterator.nextHeader();
			String key = header.getName();
			String value = header.getValue();

			headers.put(key, value);
		}
		return headers;
	}

	private void setHeaders(HttpGet httpRequest, HashMap<String, String> map) {
		if (httpRequest == null || map == null)
			return;

		Set<String> keys = map.keySet();
		Iterator<String> keyIter = keys.iterator();
		while (keyIter.hasNext()) {
			String key = keyIter.next();
			String value = map.get(key);

			httpRequest.setHeader(key, value);
		}
	}

	private void setHeaders(HttpPost httpRequest, HashMap<String, String> map) {
		if (httpRequest == null || map == null)
			return;

		Set<String> keys = map.keySet();
		Iterator<String> keyIter = keys.iterator();
		while (keyIter.hasNext()) {
			String key = keyIter.next();
			String value = map.get(key);

			httpRequest.setHeader(key, value);
		}
	}

}
